package com.anjingsi.tools.thread;

/**
 * @program: 不同线程交替输出
 * @description A打印5个奇数，B打印5个偶数，交替进行，如此循环50
 * @author: 安静思
 * @create: 2019-12-24 10:48
 **/
public class AlternatePrint {
    public static Object obj = new Object();
    public static boolean flag = false;
    public static void main(String[] args) throws InterruptedException {
        A a = new A(obj,3);
        a.start();
        B b = new B(obj,3);
        b.start();
        System.out.println("------------------------------------------------------------");
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 6 ; i++) {
                    if(!flag){
                        System.out.println(1);
                    }else {
                        System.out.println(2);
                    }
                    flag = !flag;
                }
            }
        }).start();
        a.interrupt();
        b.interrupt();
        System.out.println(a.isInterrupted());
        System.out.println(b.isInterrupted());

    }
}

class A extends Thread{
    private Object obj;
    private int sum;
    public A(Object obj,int sum){
        super("A");
        this.obj = obj;
        this.sum =sum;
    }
    @Override
    public void run() {
        for (int i = 0; i < sum; i++) {
            synchronized (obj){
                System.out.println(Thread.currentThread().getName()+"--打印的数字为："+1);
                obj.notify();
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class B extends Thread{
    private Object obj;
    private int sum;
    public B(Object obj,int sum){
        super("B");
        this.obj = obj;
        this.sum =sum;
    }
    @Override
    public void run() {
        for (int i = 0; i < sum; i++) {
            synchronized (obj){
                System.out.println(Thread.currentThread().getName()+"--打印的数字为："+2);
                obj.notify();
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}